package scheduler

import "go-reptile/crawler/engine"

type QueuedScheduler struct{
	requestChan chan engine.Request
	workerChan chan chan engine.Request
}

func (s *QueuedScheduler) Submit(r engine.Request) {
	s.requestChan <- r
}

func (s *QueuedScheduler) WorkerReady(w chan engine.Request) {
	s.workerChan <- w
}

func (s *QueuedScheduler) WorkerChan()(chan engine.Request) {
	return make(chan engine.Request)
}

func (s *QueuedScheduler) Run() {
	s.workerChan = make(chan chan engine.Request)
	s.requestChan = make(chan engine.Request)
	go func() {
		var requestQ []engine.Request
		var workerQ []chan engine.Request
		for {
			var activeRequest engine.Request
			var activeWorker chan engine.Request
			if len(requestQ) > 0 && len(workerQ) >0 {
				activeWorker = workerQ[0]
				activeRequest = requestQ[0]
			}
			select {
			// Submit函数会提交request，这里取，如果有先将request放入requestQ队列
			case  r	 := <- s.requestChan:
				requestQ = append(requestQ, r)
			// WorkerReady 函数会传入chan engine.Request,这里取，如果有先将chan engine.Request放入workerQ队列
			case  w := <- s.workerChan:
				workerQ = append(workerQ, w)
			// 从队列中取request 传入到workerChan, 队列中的数据减少
			case activeWorker <- activeRequest:
				workerQ = workerQ[1:]
				requestQ = requestQ[1:]
			}
		}
	}()
}
